package os

import (
	"context"
	"encoding/json"
	"github.com/shirou/gopsutil/v3/cpu"
	"github.com/shirou/gopsutil/v3/disk"
	"github.com/shirou/gopsutil/v3/mem"

	"os1/internal/svc"
	"os1/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type HandlerNameLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewHandlerNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HandlerNameLogic {
	return &HandlerNameLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *HandlerNameLogic) HandlerName(req *types.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	memory, err := mem.VirtualMemory()
	if err != nil {
		return nil, err
	}
	bytes, err := json.Marshal(&memory)
	var v types.VirtualMemoryStat
	json.Unmarshal(bytes, &v)

	swapMemory, err := mem.SwapMemory()
	marshal, err := json.Marshal(&swapMemory)
	var sv types.SwapMemoryStat
	json.Unmarshal(marshal, &sv)

	info, err := cpu.Info()

	var cpus []types.CpuInfoStat
	for _, stat := range info {
		i, err := json.Marshal(&stat)
		if err != nil {
			continue
		}
		var cpu1 types.CpuInfoStat
		json.Unmarshal(i, &cpu1)
		cpus = append(cpus, cpu1)
	}

	counters, err := disk.IOCounters()
	var ioCounters []types.IOCountersStat
	//todo 需要初始化
	ioCountersMap := make(map[string]types.IOCountersStat)
	for key, stat := range counters {
		i, _ := json.Marshal(stat)
		var io types.IOCountersStat
		json.Unmarshal(i, &io)
		ioCounters = append(ioCounters, io)
		ioCountersMap[key] = io
	}

	return &types.Response{
		SwapMemoryStat:    sv,
		VirtualMemoryStat: v,
		CpuInfoStats:      cpus,
		IOCountersStats:   ioCounters,
		IOCountersStatMap: ioCountersMap,
	}, nil
}
